package com.ny.controller;

import com.ny.entity.User;
import com.ny.service.UserService;
import com.ny.Util.JwtUtil;
import com.ny.entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    private final Map<String, Object> map = new HashMap<>();

    // 登录接口：POST /login
    @PostMapping("/login")
    public Result login(@RequestParam String username, @RequestParam String password) {
        System.out.println("=== 调试信息 ===");
        System.out.println("username: " + username);
        System.out.println("password: " + password);

        User user = userService.findUser(username, password);
        if (user != null) {
            String token = jwtUtil.generateToken(user.getUsername());
            jwtUtil.storeToken(token, user.getUsername());
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("token", token);
            resultMap.put("users", user);
            return Result.success(resultMap);
        } else {
            return Result.error("用户名和密码错误");
        }
    }
}